package cn.wolfcode.luowowo.website.web.util;

import cn.wolfcode.luowowo.cache.util.RedisKeys;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
    public static void addCookie(String key, String value, HttpServletResponse response, int time) {
        Cookie c = new Cookie(key, value);
        c.setMaxAge(time);
        c.setPath("/");
        response.addCookie(c);
    }

    public static String getToken(HttpServletRequest request, HttpServletResponse response) {
        String token = null;
        //首先从游览器拿cookie,判断用户有没有登录,如果有登录我们就把信息携带回给游览器,并延长cookie和redis的存活时间
        Cookie[] cookies = request.getCookies();
        //注意当前cookies不能为空并且有长度才进行
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    token = cookie.getValue();
                    //如果有token延时
                    CookieUtil.addCookie("token",token,response, RedisKeys.USER_LOGIN.getTime().intValue());
                }
            }
        }
        return token;
    }
}
